# -*- coding: utf-8 -*-
# article_info.py
# Created by Hardy on 26th, Jan
# Copyright 2017 杭州网川教育有限公司. All rights reserved.


from querier.esquerier import ElasticSearchQuerier
import utils.utils as utils


class ArticleInfoQuerier(ElasticSearchQuerier):

    def __init__(self, es, index, doc_type, nlp_service=None):
        super(ArticleInfoQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type
        self.nlp_service = nlp_service

    def _build_query(self, args):
        ids = args.get('ids')
        image_search = args.get('image_search', False)
        if ids is None:
            raise ValueError('message: "ids"(list of "article_id") is needed')

        query = {"query": {"terms": {"article_id": ids}}, 'from': 0, 'size': 2000}
        return query, {}, {'ids': ids, 'image_search': image_search}

    def _build_result(self, es_result, param):
        ids = param['ids']
        articles = []
        for hit in es_result['hits']['hits']:
            data = self.extract_result(hit, param['image_search'])
            articles.append((data.get('article_id'), data))
        article_dict = dict(articles)
        return {
            "infos": [article_dict.get(i, {}) for i in ids]
        }

    @staticmethod
    def extract_result(hit, image_search):
        source_ = dict(hit['_source'])

        res = {
            'id': source_['id'],
            'article_id': source_.get('article_id'),
            'biz_code': source_.get('biz_code', ''),
            'biz_name': source_.get('biz_name', ''),
            'title': utils.clean_text(source_.get('title',  '')),
            'title_seg': source_.get('title_seg', []),
            'title_simhash': source_.get('title_simhash'),
            'text_simhash': source_.get('text_simhash'),
            'url': source_.get('url'),
            'qrcode': utils.get_qrcode(source_.get('url', '')) if str(source_.get('from')) == '1' else '',
            'msg_cdn_url': source_.get('msg_cdn_url', ''),
            'keywords': source_.get('keywords', []),
            'read_num': source_.get('read_num') if source_.get('read_num', 0) < 100000 else 100001,
            'like_num':  source_.get('like_num') if source_.get('like_num', 0) < 100000 else 100001,
            'has_copyright': source_.get('has_copyright'),
            'publish_timestamp': source_.get('publish_timestamp'),
            'crawler_timestamp': source_.get('crawler_timestamp'),
            'category_weight': source_.get('category_weight'),
            'category': utils.category_smzdm_2_decode(source_.get('category', -1)),
            'category_social': utils.category_social_decode(source_.get('category_social', -1)),
            'image_num': source_.get('image_num'),
            'video_num': source_.get('video_num'),
            'text_len': source_.get('text_len'),
            'abstract': source_.get('abstract'),
            'from': source_.get('from'),
            'brands': []  # self.nlp_service.get_brands(source_.get('keywords', []))
        }

        if image_search:
            res['image_list'] = get_img_url(source_.get('image_list', []), source_['from'])

        return res


def get_img_url(img_list, from_):
    img_list_out = []
    if str(from_) == '1':
        for i in range(len(img_list)):
            if img_list[i][0:4] != 'http' and len(img_list[i]) > 4:
                img_list_out.append('http://mmbiz.qpic.cn/' + img_list[i])
    else:
        for i in range(len(img_list)):
            if len(img_list[i]) > 4:
                img_list_out.append('http://' + img_list[i])
    return img_list_out
